﻿@page "/fwmanger"
@using Blazor.Diagrams.Components
@using Blazor.Diagrams.Components.Widgets
@using Blazor.Diagrams.Core.Anchors
@using Blazor.Diagrams.Core.Geometry
@using Blazor.Diagrams.Core.PathGenerators
@using Blazor.Diagrams.Core.Routers
@using Blazor.Diagrams.Models
@using Models.Dto.SVG
@using Shared.Components.Svg
<CascadingValue Value="this" Name="Root">
    <div style="height:100%;width:100%;display:flex">
        @if (1 == 1)
        {
            <div class="dmain-left" style="width:20%">
                @* <div class="fd-field-properties-panel h-100 ppp"> *@
                <Tab>
                    <TabItem Text="模板清单">
                        <Table TItem="WorkFlowTemplate"
                               ShowExtendButtons="true" ShowExtendEditButton="true"
                               ShowToolbar="true"
                               ClickToSelect="true"
                               IsExtendButtonsInRowHeader="true"
                               IsStriped="true" IsBordered="true" IsMultipleSelect="false"
                               OnSaveAsync="OnSaveAsync"
                               OnQueryAsync="OnQueryAsync"
                               OnAddAsync="OnAddAsync"
                               OnDeleteAsync="OnDeleteAsync"
                               OnClickRowCallback="OnClickRowCallbackProduct"
                               AutoGenerateColumns="false">
                               <TableColumns>
                                   <TableColumn @bind-Field="context.WorkFlowTemplateName" Text="描述"></TableColumn>
                               </TableColumns>
                        </Table>
                    </TabItem>
                </Tab>
                @* </div> *@
            </div>
        }
        <div class="dmain-main" style="width:80%">
            @if (WorkFlowTemplate != null)
            {
                <div class="container-content" ondragover="event.preventDefault();" @ondragover:preventDefault @ondrop="OnDrop">
                    <CascadingValue Value="_blazorDiagram">
                        <DiagramCanvas>
                            <Widgets>
                                <SelectionBoxWidget />
                            </Widgets>
                        </DiagramCanvas>
                    </CascadingValue>
                </div>
            }
        </div>

    </div>
</CascadingValue>

@code {
    [Inject]
    [NotNull]
    public ISqlSugarClient? db { get; set; }
    private BlazorDiagram _blazorDiagram = new BlazorDiagram()
    {
    };
    private int? _draggedType;
    public Models.Dto.SVG.WorkFlowTemplate WorkFlowTemplate { get; set; } = new();
    public CustomNode? SelectedNode { get; set; }
    public void Init()
    {
        _blazorDiagram.RegisterComponent<CustomNode, NodeFW>();
    }
    protected override void OnInitialized()
    {
        base.OnInitialized();
        Init();
    }
    private void OnDrop(DragEventArgs e)
    {
        // if (_draggedType == null) // Unkown item
        //     return;
        var position = _blazorDiagram.GetRelativeMousePoint(e.ClientX - 87, e.ClientY - 30);
        var node = new CustomNode(position);

        node.AddPort(PortAlignment.Top);
        node.AddPort(PortAlignment.TopLeft);
        node.AddPort(PortAlignment.TopRight);
        node.AddPort(PortAlignment.Left);
        node.AddPort(PortAlignment.Right);
        node.AddPort(PortAlignment.Bottom);
        node.AddPort(PortAlignment.BottomLeft);
        node.AddPort(PortAlignment.BottomRight);

        _blazorDiagram.Nodes.Add(node);
        _draggedType = null;
    }
    public async Task OnChangeString(string a)
    {
        SelectedNode?.Refresh();
        await Task.CompletedTask;
    }
    public Task<bool> OnSaveAsync(WorkFlowTemplate obj, ItemChangedType type)
    {
        switch (type)
        {
            case ItemChangedType.Add:
                db.Insertable(obj).ExecuteReturnSnowflakeId();
                break;
            case ItemChangedType.Update:
                if (WorkFlowTemplate != null)
                {
                    var dto = _blazorDiagram.ToBlazorDiagramDto();
                    obj.Nodes = dto.Nodes;
                    obj.Links = dto.Links;
                    db.Updateable(obj).ExecuteCommand();
                }

                break;
        }
        return Task.FromResult(true);
        //db.Queryable<>(WorkFlowTemplate).ToList();
        //Func<QueryPageOptions, Task<QueryData<TItem>>>
    }
    public Task<QueryData<WorkFlowTemplate>> OnQueryAsync(QueryPageOptions options)
    {
        // IEnumerable<Product> items = Items;
        var items = db.Queryable<WorkFlowTemplate>().ToList();
        items = items ?? new List<WorkFlowTemplate>();
        // 过滤
        var isFiltered = false;
        if (options.Filters.Any())
        {
            // items = items.Where(options.Filters.GetFilterFunc<Product>());
            isFiltered = true;
        }

        // 排序
        var isSorted = false;
        if (!string.IsNullOrEmpty(options.SortName))
        {
            // var invoker = Foo.GetNameSortFunc();
            // items = invoker(items, options.SortName, options.SortOrder);
            isSorted = true;
        }

        // 设置记录总数
        var total = items.Count();
        // 内存分页
        items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();
        return Task.FromResult(new QueryData<WorkFlowTemplate>() { Items = items, TotalCount = total, IsSorted = isSorted, IsFiltered = isFiltered, IsSearch = true });
    }
    public Task<WorkFlowTemplate> OnAddAsync()
    {
        var obj = new WorkFlowTemplate() { Links = new(), Nodes = new() };
        return Task.FromResult(obj);
    }
    public async Task<bool> OnDeleteAsync(IEnumerable<WorkFlowTemplate> list)
    {
        await db.Deleteable<WorkFlowTemplate>(list).ExecuteCommandAsync();
        return true;
    }
    public async Task OnClickRowCallbackProduct(WorkFlowTemplate p)
    {
        if (WorkFlowTemplate.Id != p.Id)
        {
            WorkFlowTemplate = p;
            _blazorDiagram.Nodes.Clear();
            _blazorDiagram.Links.Clear();
            var wf = p.ToBlazorDiagram(true);
            _blazorDiagram.Nodes.Add(wf.Nodes);
            _blazorDiagram.Links.Add(wf.Links);
            _blazorDiagram.Refresh();
        }
        StateHasChanged();
        await Task.Delay(50);
    }
    public void SaveSelect()
    {
        if (WorkFlowTemplate.Id!=0)
        {
            var dto = _blazorDiagram.ToBlazorDiagramDto();
            WorkFlowTemplate.Nodes = dto.Nodes;
            WorkFlowTemplate.Links = dto.Links;
            db.Updateable(WorkFlowTemplate).ExecuteCommand();
        }
    }
}
